const app = getApp();
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '标题',
    sign_status: '待激活',
    type: '上课签到',
    signList: [{
        activity: '上课签到',
        // 待激活，进行中，查看
        status: '查看'
      },
      {
        activity: '下课签到',
        status: '进行中'
      },
    ],
    onCalendar: false,
    actList: [],
    // 签到的个数
    launch_len: 0,
    x: wx.getSystemInfoSync().windowWidth,
    y: wx.getSystemInfoSync().windowHeight * (0.2),
    lid: '',
    duration: '',
    actId: '',
    tid: '',
    endTime:'',
    status:'',
    // 列表日期
    listDate: '今日签到',
    day: '',
    month: '',
    createTime: util.formatDate(new Date()),
    // 含有签到列表的当前月的日期
    dateList: [],
    style: [],
    avatarInfo: '',
    signways: [{
      id: 1,
      name: '二维码',
      checked: true
    }, {
      id: 2,
      name: '拍照'
    }],
    wayIndex: 1,

    choosen: {
      latitude: 0,
      longitude: 0
    },
    flag1: false,

    scopelist: [100, 200, 300, 400, 500, 1000, 1500, 2000, 2500, 3000],
    scopeIndex: 4,

    chooseview: true,

    hintTitle: '确定激活此签到？请选择激活方式',
    tmp: '',
    //新增签到环节
    activities: ["签到", "签退"],
    activityIndex: "0",
    timelist: [1, 2, 3, 4, 5, 10, 15, 20, 25, 30],
    timeIndex: "0",
    actid:'0',
    sign_stop_type:0,
  },
  
  //打开新增环节对话框
  newLink(e){
    this.data.actId=e.currentTarget.dataset.actid
    this.setData({
      modalName:e.currentTarget.dataset.target,
      actId:this.data.actId
    })

  },
  //关闭新增环节对话框
  hideNewLink(e){
    this.setData({
      modalName:null
    })
  },
  //处理环节的选择
  bindActivityChange(e){
    this.setData({
      activityIndex:e.detail.value
    })
   
  },
  //处理环节的时间选择
  bindTimeChange(e){
    this.setData({
      timeIndex:e.detail.value
    })
  },
 
  //确定修改时限
  async changeTimelast(e){
    this.data.lid=e.currentTarget.dataset.lid
    console.log(this.data.lid);
    this.data.timeIndex=e.detail.value
    this.setData({
      timeIndex: this.data.timeIndex
    })
    console.log(this.data.timeIndex);
    
    await wx.User.updateLinkDuration({
      data:{
        duration:this.data.timelist[this.data.timeIndex],
        lid:this.data.lid
      }
    })
    this.onShow()
  },
  //新增环节
  async determineLink(){
    var param={}
    console.log(param);
    param.actid=this.data.actId+''
    param.duration=this.data.timelist[this.data.timeIndex]+''
    param.linktype=parseInt(this.data.activityIndex)+1
    param.rangement=0
    console.log(param);
    await wx.User.addLink({
      data: param
    })
    this.hideNewLink()
    this.onShow()
  },
  bindScopeChange(e) {
    this.setData({
      scopeIndex: e.detail.value
    })
  },

  chooseLocation: function () {
    // let that = this
    wx.chooseLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          choosen: res,
          flag1: true
        })
      },
    })
  },


  onwayChange(e) {
    this.setData({
      wayIndex: e.detail.key,
    })
  },

  //下拉刷新
  onPullDownRefresh: async function () {
    if (wx.User.token == null || wx.User.token == '') {

    } else {
      this.pullDown()
    }
  },

  // 刷新函数
  pullDown: function () {
    wx.showLoading({
      title: '加载中',
    })
    new Promise(async (resolve, reject) => {
      // 查找列表
      await wx.User.findActByTid({
        data: {
          tid: this.data.tid,
          createTime: this.data.createTime
        }
      })
      resolve(wx.getStorageSync('actList'))
    }).then(res => {
      this.setData({
        actList: res,
        launch_len: res.length

      })
      wx.hideLoading({
        success: (res) => {},
      })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh({
      success: (res) => {},
    })
  },

  gotocode: function (e) {
    this.setData({
      actId: e.currentTarget.dataset.actid,
      lid: e.currentTarget.dataset.lid,
      duration: e.currentTarget.dataset.duration,
      linkType: e.currentTarget.dataset.linktype,
      className: e.currentTarget.dataset.classname,
      title: e.currentTarget.dataset.title,
      endTime:e.currentTarget.dataset.endtime,
      status:e.currentTarget.dataset.status,
      cid:e.currentTarget.dataset.cid
    })

    wx.navigateTo({
      url: './sign_code?actId=' + this.data.actId + '&lid=' + this.data.lid + '&duration=' + this.data.duration + '&title=' + this.data.title + '&linkType=' + this.data.linkType + '&className=' + this.data.className + '&endTime='+this.data.endTime + '&status=' + this.data.status+'&cid='+this.data.cid,
    })
  },

  gotophoto(e) {
    this.setData({
      actId: e.currentTarget.dataset.actid,
      lid: e.currentTarget.dataset.lid,
      duration: e.currentTarget.dataset.duration,
      cid: e.currentTarget.dataset.cid
    })

    wx.navigateTo({
      url: '/pages/photo/takePhotos?cid=' + this.data.cid + '&lid=' + this.data.lid + '&duration=' + this.data.duration,
    })
  },

  monthChange: async function (e) {
    const year = e.detail.currentYear
    if (e.detail.currentMonth < 10) {
      this.setData({
        tmp: '0' + e.detail.currentMonth
      })
    } else {
      this.setData({
        tmp: e.detail.currentMonth
      })
    }
    const date = year + '-' + this.data.tmp
    await this.selectActivityByMonth(date)
  },


  // 日历组件点击显示和隐藏
  transmit() {
    if (this.data.onCalendar == false) {
      this.setData({
        onCalendar: true
      })
      if (wx.pageScrollTo) {
        wx.pageScrollTo({
          scrollTop: 0,
        })
      }
    } else {
      this.setData({
        onCalendar: false
      })
    }
  },
  //
  // 点击显示删除签到活动弹框
  showDeleteDialog(e) {
    this.setData({
      actId: e.currentTarget.dataset.cid,
      modalName: e.currentTarget.dataset.target
    })
  },
  // 隐藏删除签到活动弹框
  hideDeleteDialog(e) {
    this.setData({
      modalName: null
    })
  },
  // 删除签到活动
  deleteActList: async function (e) {
    await wx.User.deleteActivity({
      data: {
        actid: this.data.actId
      }
    })
    this.hideDeleteDialog()
    this.onShow()
  },


  // 点击日历事件
  dayClick: async function (event) {
    const year = event.detail.year;
    const month = event.detail.month;
    this.data.month = month;
    if (event.detail.day < 10) {
      this.data.day = '0' + event.detail.day;
    } else {
      this.data.day = event.detail.day;
    }
    if (month < 10) {
      this.data.month = '0' + month;
    } else {
      this.data.month = month;
    }
    this.data.createTime = year + '-' + this.data.month + '-' + this.data.day
    wx.setStorageSync('createTime', this.data.createTime)
    await wx.User.findActByTid({
      data: {
        tid: this.data.tid,
        createTime: this.data.createTime
      }
    })
    var style = [];
    //先把含有签到的日期设置颜色
    style.push({
      month: 'current',
      day: event.detail.day,
      color: 'white',
      background: '#728EFF'
    })
    for (let i = 0; i < this.data.dateList.length; i++) {
      if (this.data.dateList[i] != event.detail.day) {
        style.push({
          month: 'current',
          day: this.data.dateList[i],
          color: 'white',
          background: '#00B26A'
        })
      }
    }
    this.setData({
      style: style,
      listDate: month + '月' + this.data.day + '日',
      actList: wx.getStorageSync('actList'),
      launch_len: wx.getStorageSync('actList').length
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    app.editTabbar();
    //当前日期
    const timestamp = Date.parse(new Date());
    const date = new Date(timestamp);
    const Y = date.getFullYear();
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    wx.setStorageSync('createTime', Y + '-' + M + '-' + D)

    if (wx.User.token == null || wx.User.token == '') {

    } else {
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        tid: wx.getStorageSync('userinfo').uid
      })
      // 获取当前月的有签到列表的日期
      await this.selectActivityByMonth(util.formatMonth(new Date()))
      var that = this
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            screenHeight: res.windowHeight,
            screenWidth: res.windowWidth
          })
        },
      })
      this.data.x = this.data.screenWidth * 0.1
      this.data.y = this.data.screenHeight * 0.1
      this.setData({
        screenWidth: this.data.screenWidth,
        tid: wx.getStorageSync('userinfo').uid,
        avatarInfo: wx.getStorageSync('avatarInfo').avatarUrl,
        createTime: util.formatDate(new Date()),
        x: this.data.x,
        y: this.data.y
      })
      this.onShow()
      wx.stopPullDownRefresh();
    }
  },
  // 显示激活签到的弹框
  showModalDialog: async function (e) {
    var hintTitle = '确定激活此签到？'
    var picviewflag = false
    // 无定位+有名单
    if (e.currentTarget.dataset.rangement == 0 && e.currentTarget.dataset.cid != '') {
      hintTitle = '确定激活此签到？请选择激活方式'
      picviewflag = true
    }
    this.setData({
      actId: e.currentTarget.dataset.actid,
      lid: e.currentTarget.dataset.lid,
      duration: e.currentTarget.dataset.duration,
      modalName: e.currentTarget.dataset.target,
      chooseview: e.currentTarget.dataset.rangement == 0 ? true : false,
      cid: e.currentTarget.dataset.cid,
      hintTitle: hintTitle,
      picviewflag: picviewflag,
      linkType: e.currentTarget.dataset.linktype,
      className: e.currentTarget.dataset.classname,
      title: e.currentTarget.dataset.title
    })
  },
  // 隐藏激活签到的弹框
  hideModalDialog(e) {
    this.setData({
      modalName: null
    })
  },
  // 确定激活签到
  toCode: async function (event) {
    await wx.User.updateLinkStatus({
      data: {
        lid: this.data.lid,
        status: 1,
        duration: this.data.duration
      }
    })
    var signtypedata = wx.getStorageSync('signtypedata')
    this.hideModalDialog()
    if (this.data.wayIndex == 2 && this.data.picviewflag) {
      wx.navigateTo({
        url: '/pages/photo/takePhotos?cid=' + this.data.cid + '&lid=' + this.data.lid + '&duration=' + this.data.duration,
      })
    } else {
      // 522是二维码签到
      if (signtypedata == 522) {
        // linkType==1?'签到':'签退' 
        wx.navigateTo({
          url: './sign_code?actId=' + this.data.actId + '&lid=' + this.data.lid + '&duration=' + this.data.duration + '&title=' + this.data.title + '&linkType=' + this.data.linkType + '&className=' + this.data.className,
        })
      }
    }
    this.onShow()
  },
  // 点击查看签到活动的详情
  showSignInfo: function (e) {
    this.setData({
      actId: e.currentTarget.dataset.actid,
      lid: e.currentTarget.dataset.lid,
      cname:e.currentTarget.dataset.fname,
    })
    wx.navigateTo({
      url: '/pages/teacher/sign_result?actId=' + this.data.actId + '&lid=' + this.data.lid+ '&cname=' + this.data.cname,
    })
  },


  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },
  // 切换月份
  changeMonth: async function (e) {
    const year = e.detail.currentYear
    if (e.detail.currentMonth < 10) {
      this.setData({
        tmp: '0' + e.detail.currentMonth
      })
    } else {
      this.setData({
        tmp: e.detail.currentMonth
      })
    }
    const date = year + '-' + this.data.tmp
    await this.selectActivityByMonth(date)
  },
  // 返回一个月中含有签到列表的日期
  selectActivityByMonth: async function (e) {
    await wx.User.selectActivityByMonth({
      data: {
        tid: wx.getStorageSync('userinfo').uid,
        month: e
      }
    })
    this.setData({
      dateList: wx.getStorageSync('dateList'),
    })
    let style = new Array;
    for (let i = 0; i < this.data.dateList.length; i++) {
      style.push({
        month: 'current',
        day: this.data.dateList[i],
        color: 'white',
        background: '#00B26A'
      });
    }
    if (e.substring(0, 4) == wx.getStorageSync('createTime').substring(0, 4) && e.substring(5, 7) == wx.getStorageSync('createTime').substring(5, 7)) {
      style.push({
        month: 'current',
        day: parseInt(wx.getStorageSync('createTime').substring(8, 10)),
        color: 'white',
        background: '#728eff'
      })
    }
    this.setData({
      style: style
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {

    if (wx.User.token == null || wx.User.token == '') {

    } else {
      this.setData({
        tid: wx.getStorageSync('userinfo').uid,
        loginflag: app.globalData.loginflag
      })
      if (this.data.tid == undefined && this.data.loginflag == false) {
        app.globalData.loginflag = true
      }
      new Promise(async (resolve, reject) => {
        // 查找列表
        await wx.User.findActByTid({
          data: {
            tid: this.data.tid,
            createTime: this.data.createTime
          }
        })
        resolve(wx.getStorageSync('actList'))
      }).then(res => {
        this.setData({
          avatarInfo: wx.getStorageSync('avatarInfo').avatarUrl,
          actList: res,
          launch_len: res.length
        })
        wx.hideLoading({
          success: (res) => {},
        })
      })
      wx.hideNavigationBarLoading() //完成停止加载
    }

  },

  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true,

    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  navtoInfo: function (e) {
    var index = e.currentTarget.id;
    if (this.data.signList[index].status == '查看') {
      wx.navigateTo({
        url: '/pages/teacher/sign_result',
      })
    } else if (this.data.signList[index].status == '进行中') {
      wx.navigateTo({
        url: '/pages/teacher/sign_info',
      })
    }
  },
})